import { useIntl } from '@umijs/max';
import { ConfigProvider, Tooltip } from 'antd';
import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
import { fitChartSize } from '../utils/tools';
import Styles from './EventInfo.less';

export interface GradeIEvent {
  eventKey?: number;
  eventRank?: React.ReactNode;
  eventTime?: string;
  eventStatus?: string;
  eventPloy: string | null | undefined;
  eventGrade?: string;
  eventDes?: string;
  eventID?: string;
  eventType?: string;
  eventLocation?: string;
  eventName?: string;
}

export interface EventInfoProps {
  eventType?: string;
  eventData: GradeIEvent[];
  isScrolling?: boolean;
}

export interface EventInfoRef {
  pauseScrolling: () => void;
  resumeScrolling: () => void;
}

const EventInfo = forwardRef<EventInfoRef, EventInfoProps>(
  ({ eventType, eventData, isScrolling = false }, ref) => {
    const [scrolling, setScrolling] = useState(isScrolling);
    const [scrollTop, setScrollTop] = useState(0);
    const warperRef = useRef<HTMLDivElement>(null);
    const contentWrapperRef = useRef<HTMLDivElement>(null);
    const childDom1Ref = useRef<HTMLDivElement>(null);
    const childDom2Ref = useRef<HTMLDivElement>(null);
    const speed = 30;
    const intl = useIntl();
    useEffect(() => {
      setScrolling(isScrolling);
    }, [isScrolling]);

    useEffect(() => {
      if (childDom1Ref.current && childDom2Ref.current) {
        childDom2Ref.current.innerHTML = childDom1Ref.current.innerHTML;
      }

      let timer: NodeJS.Timeout;
      if (scrolling && warperRef.current && childDom1Ref.current) {
        timer = setInterval(() => {
          if (warperRef.current && childDom1Ref.current) {
            if (warperRef.current.scrollTop >= childDom1Ref.current.scrollHeight) {
              warperRef.current.scrollTop = 0;
            } else {
              warperRef.current.scrollTop++;
            }
          }
        }, speed);
      }

      return () => {
        clearInterval(timer);
      };
    }, [scrolling, eventData.length]);

    const hoverHandler = (flag: boolean) => {
      if (isScrolling) {
        setScrolling(flag);
      }
    };

    useImperativeHandle(ref, () => ({
      pauseScrolling: () => {
        if (warperRef.current) {
          setScrolling(false);
          setScrollTop(warperRef.current.scrollTop);
        }
      },
      resumeScrolling: () => {
        if (warperRef.current) {
          warperRef.current.scrollTop = scrollTop;
          setScrolling(true);
        }
      },
    }));

    const getHeaders = () => {
      let headers = ['序号', '时间', '状态', '策略执行事件'];

      if (eventType === 'warning') {
        headers = [
          intl.formatMessage({ id: 'bigdata.S/N' }),
          intl.formatMessage({ id: 'bigdata.alarm' }),
          intl.formatMessage({ id: 'bigdata.eventName' }),
          intl.formatMessage({ id: 'bigdata.location' }),
        ];
      }

      return headers;
    };

    const headerElements = getHeaders().map((header, index) => (
      <div
        key={index}
        className={`${Styles['event-info-header-cell']} ${
          index === 0 ? Styles['narrow-column'] : ''
        } ${index === 1 ? Styles['narrow-column--left'] : ''}`} // 添加条件判断
      >
        {header}
      </div>
    ));

    const rowElements = eventData.map((event, index) => (
      <div key={event.eventKey || index} className={Styles['event-info-row']}>
        <div className={`${Styles['event-info-cell']} ${Styles['narrow-column']}`}>
          {event.eventRank}
        </div>
        <div className={`${Styles['event-info-cell']} ${Styles['narrow-column--left']}`}>
          {eventType === 'warning' ? event.eventType : event.eventTime}
        </div>
        <div className={Styles['event-info-cell']}>
          <Tooltip
            arrow={false}
            title={event.eventName}
            overlayClassName={Styles.customTooltip}
            overlayInnerStyle={{
              backgroundColor: 'rgba(3, 25, 54, 0.9)',
              border: '1px solid #4c8fce',
              color: '#C4D4F1',
              fontSize: fitChartSize(12),
            }}
          >
            <span className={Styles['truncate-text']}>
              {eventType === 'warning' ? event.eventName : event.eventDes}
            </span>
          </Tooltip>
        </div>
        <div className={Styles['event-info-cell']}>
          <Tooltip
            arrow={false}
            title={event.eventLocation}
            overlayClassName={Styles.customTooltip}
            overlayInnerStyle={{
              backgroundColor: 'rgba(3, 25, 54, 0.9)',
              border: '1px solid #4c8fce',
              color: '#C4D4F1',
              fontSize: fitChartSize(12),
            }}
          >
            <span className={Styles['truncate-text']}>{event.eventLocation}</span>
          </Tooltip>
        </div>
      </div>
    ));

    return (
      <div className={Styles['event-info-container']}>
        <ConfigProvider
          theme={{
            components: {
              Table: {
                cellPaddingBlock: 8,
                cellFontSize: fitChartSize(12),
                algorithm: true,
              },
            },
          }}
        >
          <div className={Styles['event-info-header']}>{headerElements}</div>
          <div
            className={Styles['event-info-body']}
            ref={warperRef}
            onMouseOver={() => hoverHandler(false)}
            onMouseLeave={() => hoverHandler(true)}
          >
            <div className={Styles['content-wrapper']} ref={contentWrapperRef}>
              <div className={Styles['event-info-content']} ref={childDom1Ref}>
                {rowElements}
              </div>
              <div className={Styles['event-info-content']} ref={childDom2Ref}></div>
            </div>
          </div>
        </ConfigProvider>
      </div>
    );
  },
);

export default EventInfo;
